import re

from flask import Blueprint,request,make_response,jsonify,redirect
from flask_restful import reqparse
from util.myjwt import myjwt
from util.captcha.captcha import captcha
import json, random, time, requests
from util.myredis import r
from util.smscode import sms_code
from models.user import *
from util.comm import get_ali_object, md5


rbac_blue = Blueprint("rbac",__name__)

# 获取角色
@rbac_blue.route("/getrole")
def getrole():
    sql = roles.query.all()
    list = [{'id': i.id, 'name': i.name} for i in sql]
    return jsonify({'code': 200, 'data': list})

# 获取角色资源
@rbac_blue.route("/getresource")
def getresource():
    rid = request.args.get('roleid')
    res = resource.query.filter(resource.pid !=0 ).all()
    list = []
    for i in res:
        list.append({'key':i.id,'label':i.username})
    role = roles_resource.query.filter_by(roleid=rid).all()
    vlist = []
    for i in role:
        vlist.append(i.resourceid)

    return jsonify({'code':200,'rlist':list,'vlist':vlist})
@rbac_blue.route("/postresource", methods=['POST'])
def postresource():
    data = json.loads(request.data)
    roleid = data['roleid']
    value = data['resid']
    roles_resource.query.filter_by(roleid=roleid,typeid=0).delete()
    db.session.commit()
    for i in value:
        rr = roles_resource(roleid=roleid, resourceid=i)
        db.session.add(rr)
        db.session.commit()
    return jsonify({'code': 200, 'msg': 'ok'})

@rbac_blue.route('/leftmenu')
def leftmenu():
    roleid = request.args.get('roleid')
    sql = db.session.execute("select re.*,pre.username as pname from roles_resource as rr left join resource as re on rr.resourceid=re.id left join resource as pre on pre.id = re.pid where rr.roleid=%d and re.type=1"%int(roleid))
    res = list(sql)
    print(res)
    list1 = []
    mlist = []
    for i in res:
        print(1)
        if i[5] not in mlist:
            list1.append({'id':i[5],'name':i[7],'son':[]})
            mlist.append(i[5])
    for j in res:
        for index,p in enumerate(list1):
            if j[5] == p['id']:
                list1[index]['son'].append({'id':j[0],'name':j[3],'url':j[4]})
    print(list1)
    return jsonify({'code':200,'list':list1})



@rbac_blue.route('/adminlogin',methods=['POST'])
def adminlogin():
    data = json.loads(request.data)
    name = data['name']
    pwd = data['pwd']
    sql = admin_user.query.filter_by(name=name).first()
    if sql:
        newpwd = md5(pwd)
        if newpwd == sql.pwd:
            data = {'data':{'userid':sql.id,'roleid':sql.roleid,'exp':int(time.time())}}
            token = myjwt.jwt_encode(data)
            return jsonify({'code':200,'msg':'登录成功','token': token, 'uid': sql.id,'roleid':sql.roleid})
        return jsonify({'code':10023,'msg':'密码错误'})
    print(1)
    password = md5(pwd)
    user = admin_user(name=name,pwd=password)
    db.session.add(user)
    db.session.commit()

    return jsonify({'code':'10023','msg':'注册成功'})


# 用户退出接口
@rbac_blue.route("/exitlogin")
def exitlogin():
    data = json.loads(request.data)
    token = data['token']
    print(token)
    key = "logoutlist"
    r.sortedset_add(key,token,int(time.time()))
    return jsonify({"code": 200, 'mes': '退出成功'})



@rbac_blue.route('/gettype')
def gettype():
    sql = db.session.execute("select ro.id as rid,re.id,ro.name,re.username from roles_resource as rr inner join roles as ro on rr.roleid = ro.id inner join resource as re on rr.resourceid=re.id where rr.typeid=0")
    list = [{"id":i.id,'rid':i.rid,'name':i.name,'username':i.username}for i in sql]
    return jsonify({'code':200,'data':list})


@rbac_blue.route('/getbutton')
def getbutton():
    sql = button.query.all()
    list = [{'id':i.id,'name':i.name}for i in sql]
    return jsonify({'code':200,'data':list})


@rbac_blue.route('/postresourcetype',methods=['POST'])
def postresourcetype():
    data = json.loads(request.data)
    roleid = data['roleid']
    value = data['resid']
    types1 = data['type']
    print(data)

    roles_resource.query.filter(roles_resource.roleid==roleid ,roles_resource.resourceid==value,roles_resource.typeid!=0).delete()

    db.session.commit()
    for j in types1:
        print(2)
        print(j)
        rr = roles_resource(roleid=roleid,resourceid=value,typeid=j)
        db.session.add(rr)
        db.session.commit()
    return jsonify({'code':200,'msg':'ok'})

# 审核
# @rbac_blue.route('/audit')
def audit():
    sql = db.session.execute("select id from admin_user where username='审核员'")
    while True:

        for i in sql:
            code = r.list_lpop('projectkey')
            if code != None:
                code = code.decode()
                # r.list_rpush('auditcode',code)
                number = hash(int(code))%3
                print(number)
                tablename = 'project'
                if number > 0:
                    tablename = tablename +str(number)
                tablename = globals().get(f'{tablename}')
                tablename.query.filter_by(code=code).update({'auditid':i.id})
                db.session.commit()

    # print(sql.id)
        return 'ok'


@rbac_blue.route('/getaudit')
def getaudit():
    auditid = request.args.get('userid')
    p1 = db.session.query(project).filter(project.status == 0, project.auditid == auditid)
    p2 = db.session.query(project1).filter(project1.status == 0, project1.auditid == auditid)
    p3 = db.session.query(project2).filter(project2.status == 0, project2.auditid == auditid)
    audit = p1.union(p2).union(p3).all()
    list = []
    print(audit)
    for i in audit:
        list.append({'code': str(i.code),
            'name': i.name,
            'title': i.title,
            'descs': i.descs,
            'type': i.type,
            'money': i.money,
            'mobile': i.mobile,
            'trade': i.trade,
            'status': i.status,
            'userid': i.userid,
            'create_time':str(i.create_time),
            'update_time':str(i.update_time)
                     })
    print('!!!!!!!!!!!!!',list)
    return jsonify({'code':200,'data':list})


@rbac_blue.route('/getshen')
def getshen():
    code = request.args.get('code')
    print(code)
    typeid = request.args.get('typeid')
    number = hash(int(code)) % 3
    print(number)
    tablename = 'project'
    if number > 0:
        tablename = tablename + str(number)
    tablename = globals().get(f'{tablename}')
    tablename.query.filter_by(code=code).update({'status': typeid})
    db.session.commit()
    return jsonify({'code': 200, 'msg': 'ok'})

@rbac_blue.route('/getcode')
def getprogectcode():
    code = request.args.get('code')
    number = hash(int(code)) % 3
    tablename = 'project'
    if number > 0:
        tablename = tablename + str(number)
    tablename = globals().get(f'{tablename}')
    pro = tablename.query.filter_by(code=code).first()
    list = []
    print('**********',pro.code)

    list.append({
        'code': str(pro.code),
        'name': pro.name,
        'title': pro.title,
        'descs': pro.descs,
        'type': pro.type,
        'money': pro.money,
        'mobile': pro.mobile,
        'trade': pro.trade,
        'status': pro.status,
        'userid': pro.userid,
        'create_time': str(pro.create_time),
        'update_time': str(pro.update_time)
    })

    return jsonify({'code':200,'data':list})


















